package com.chenhj.interceptor;

import java.util.List;

import javax.xml.namespace.QName;

import org.apache.cxf.binding.soap.SoapHeader;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.headers.Header;
import org.apache.cxf.helpers.DOMUtils;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.chenhj.utils.EncryptUtil;



public class ValidateOutInterceptor extends AbstractPhaseInterceptor<SoapMessage> {
	
	private String username;
	private String password;
	
	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
	
	
	public ValidateOutInterceptor(String phase) {
		super(phase);
	}

	public ValidateOutInterceptor(String username, String password) {
		super(Phase.PREPARE_SEND);  
		this.username = username;
		this.password = password;
	}

	@Override
	public void handleMessage(SoapMessage message) throws Fault {
		
		
		Document doc = (Document) DOMUtils.createDocument();
		Element root = doc.createElement("auth");
		Element child1 = doc.createElement("username");
		Element child2 = doc.createElement("password");
		String newpassword = EncryptUtil.strToEncrypt(this.password, "MD5", 1024, this.username);
		System.out.println("newpassword="+newpassword);
		
		child1.setTextContent(this.username);
		child2.setTextContent(newpassword);
	
		root.appendChild(child1);
		root.appendChild(child2);
		SoapHeader head = new SoapHeader(new QName(""), root);
		List<Header> headers = message.getHeaders();
		headers.add(head);
	}

}
